package com.zn.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.zn.util.AESEncrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

/**
 * @author YinJiaWei
 * @version 2018/10/10 14:12
 * @描述 响应参数统一加密
 */
@Configuration
public class EncryptHandleFilter extends ZuulFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(EncryptHandleFilter.class);
    @Value("${aesKey}")
    private String aesKey;
    @Value("${unwanted.encrypt.method.uri}")
    private String unwantedEncryptUri;
    @Override
    public String filterType() {
        return "post";
    }
    @Override
    public int filterOrder() {
        return 999;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 将响应出去的参数统一加密
     * @return
     */
    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String requestURI=request.getRequestURI().toString();
        LOGGER.info(String.format("EncryptHandleFilter..... %s request to %s uri: %s", request.getMethod(), request.getRequestURL().toString(),requestURI));
        try {
            List<String> uriList= Arrays.asList(unwantedEncryptUri.split(","));
            if(!uriList.contains(requestURI)){
                long begin=System.currentTimeMillis();
                InputStream stream = context.getResponseDataStream();
                String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
                if(body.length()<500){LOGGER.info("EncryptHandleFilterBody............."+body);}
                String enctyptStr= AESEncrypt.aesEncrypt(body, aesKey);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("enctyptData", enctyptStr);
                if(jsonObject.toString().length()<500){LOGGER.info("ResponseBody..........."+jsonObject.toString());}
                context.setResponseBody(jsonObject.toString());
                long end=System.currentTimeMillis();
                LOGGER.info("EncryptHandleFilterTime.....:" +(end-begin));
            }
        }
        catch (Exception e) {
            LOGGER.error("run....",e);
        }
        return null;
    }
}
